package com.hxzy.config.security;

import cn.hutool.core.util.StrUtil;
import com.hxzy.service.system.impl.TokenService;
import com.hxzy.vo.AdminLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义令牌验证器
 */
@Component
public class JwtTokenValidator extends OncePerRequestFilter {


    @Autowired
    private TokenService  tokenService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //取得令牌
        String jwtToken=request.getHeader("Authorization");

        //如果有令牌，验证令牌有效性
        if(StrUtil.isNotBlank(jwtToken)){
            //对swagger的请求进行放行
            if(!jwtToken.startsWith("Basic")){
                AdminLoginVO adminLoginVO = this.tokenService.validatorToken(jwtToken);
                if(adminLoginVO!=null){
                    //放到 spring security的本地线程池中
                    UsernamePasswordAuthenticationToken  userToken=new UsernamePasswordAuthenticationToken(adminLoginVO,adminLoginVO.getPassword(),adminLoginVO.getAuthorities());

                    userToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    // 本地线程池中存放数据
                    SecurityContextHolder.getContext().setAuthentication(userToken);

                }
            }


        }

        //放行,交给后面的spring security Filter来处理
        filterChain.doFilter(request,response);
    }
}
